package com.rtsapp.server.domain.mysql.hibernate;

import com.rtsapp.server.domain.mysql.hibernate.impl.AsyncTransactionWorker;
import com.rtsapp.server.domain.mysql.hibernate.impl.AysncTransaction;
import com.rtsapp.server.domain.mysql.hibernate.impl.DirectTransaction;
import com.rtsapp.server.module.AbstractModule;
import com.rtsapp.server.module.Module;
import com.rtsapp.server.domain.mysql.hibernate.impl.HibernateUtils;
import com.rtsapp.server.logger.Logger;

public class HibernateModule extends AbstractModule {

	private static final Logger logger =com.rtsapp.server.logger.LoggerFactory.getLogger( HibernateModule.class );

	private AsyncTransactionWorker worker;
	private int asyncQueueSize = 102400 ;//TODO 需改为配置文件
	private String hibernateCfgFile = "cfg/hibernate.cfg.xml";

	
	public void setAsyncQueueSize( int asyncQueueSize ){
		this.asyncQueueSize = asyncQueueSize;
	}
	
	public void setHibernateCfgFile( String hibernateCfgFile ){
		this.hibernateCfgFile  = hibernateCfgFile;
	}
	
	
	@Override
	public boolean initialize(Module parentModule) {
		
		
		
		return true;
	}


	@Override
	public boolean start() {

		try {
			HibernateUtils.init(this.hibernateCfgFile);

			worker = new AsyncTransactionWorker(asyncQueueSize);
			worker.start();

			logger.info("HibernateModule started");
			return true;
		}catch( RuntimeException ex ){
			logger.error("HibernateModule start error", ex );
			return false;
		}
	}

	@Override
	public void stop() {

		//这里会立即返回，线程不会结束，是否考虑返回future，等future结束后再返回?
		worker.stop();
		
		logger.info( "HibernateModule stoped" );
		
	}

	@Override
	public void destroy() {
		
	}


	/**
	 * @return 返回同步的Transaction
	 */
	public IEntityTransaction getTransaction(  ){
		return new DirectTransaction( );
	}


	/**
	 * @return 返回异步的Transaction
	 */
	public IEntityTransaction getAysncTransaction(){
		return new AysncTransaction( worker );
	}


	
	
}
